/**
 * 版本对比组件
 */
const timeHelper = require('../../../helpers/time_helper.js');
const cloudHelper = require('../../../helpers/cloud_helper.js');

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    // 资源ID
    resourceId: {
      type: String,
      value: ''
    },
    
    // 资源名称
    resourceName: {
      type: String,
      value: ''
    },
    
    // 资源类型
    resourceType: {
      type: String,
      value: ''
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    // 版本列表
    versions: [],
    
    // 选中的版本A
    versionA: '',
    versionAName: '请选择版本',
    
    // 选中的版本B
    versionB: '',
    versionBName: '请选择版本',
    
    // 版本差异数据
    diffData: null,
    
    // 加载状态
    isLoading: true,
    
    // 比较中状态
    isComparing: false,
    
    // 错误信息
    error: null,
    
    // 是否展开详情
    isExpanded: false,
    
    // 是否显示比较结果
    showDiff: false,
    
    // 版本A的索引
    versionAIndex: 0,
    
    // 版本B的索引
    versionBIndex: 1
  },

  /**
   * 生命周期函数
   */
  lifetimes: {
    attached() {
      this._loadVersions();
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    /**
     * 加载版本数据
     */
    async _loadVersions() {
      if (!this.properties.resourceId) {
        this.setData({
          isLoading: false,
          error: '缺少资源ID'
        });
        return;
      }

      this.setData({ isLoading: true, error: null });

      try {
        // 使用云函数替代Biz调用
        const result = await cloudHelper.callCloudData('research/get_resource_versions', {
          resourceId: this.properties.resourceId
        });
        const versions = result || [];
        
        // 格式化版本数据
        const formattedVersions = versions.map(item => {
          return {
            ...item,
            CREATE_TIME_DISPLAY: item.CREATE_TIME ? timeHelper.fmtDateTimeCN(item.CREATE_TIME) : '未知'
          };
        });
        
        // 默认选择最近的两个版本
        let versionA = '';
        let versionB = '';
        let versionAName = '请选择版本';
        let versionBName = '请选择版本';
        let versionAIndex = 0;
        let versionBIndex = 1;
        
        if (formattedVersions.length >= 2) {
          versionA = formattedVersions[0].VERSION;
          versionAName = formattedVersions[0].VERSION_NAME || versionA;
          versionB = formattedVersions[1].VERSION;
          versionBName = formattedVersions[1].VERSION_NAME || versionB;
        } else if (formattedVersions.length === 1) {
          versionA = formattedVersions[0].VERSION;
          versionAName = formattedVersions[0].VERSION_NAME || versionA;
        }
        
        this.setData({
          versions: formattedVersions,
          versionA,
          versionAName,
          versionB,
          versionBName,
          versionAIndex,
          versionBIndex,
          isLoading: false
        });
      } catch (err) {
        console.error('获取资源版本信息失败', err);
        this.setData({
          isLoading: false,
          error: '加载版本信息失败: ' + (err.message || '未知错误')
        });
      }
    },

    /**
     * 刷新版本数据
     */
    refreshData() {
      this._loadVersions();
    },

    /**
     * 展开/收起详情
     */
    toggleExpand() {
      this.setData({
        isExpanded: !this.data.isExpanded,
        // 收起时隐藏比较结果
        showDiff: this.data.isExpanded ? false : this.data.showDiff
      });
    },

    /**
     * 选择版本A
     */
    onSelectVersionA(e) {
      const index = e.detail.value;
      const version = this.data.versions[index].VERSION;
      const versionName = this.data.versions[index].VERSION_NAME;
      
      // 防止与版本B相同
      if (version === this.data.versionB) {
        const otherIndex = this.data.versions.findIndex(v => v.VERSION !== version);
        if (otherIndex !== -1) {
          const otherVersion = this.data.versions[otherIndex];
          this.setData({
            versionA: version,
            versionAName: versionName,
            versionAIndex: index,
            versionB: otherVersion.VERSION,
            versionBName: otherVersion.VERSION_NAME,
            versionBIndex: otherIndex,
            showDiff: false
          });
        }
      } else {
        this.setData({
          versionA: version,
          versionAName: versionName,
          versionAIndex: index,
          showDiff: false
        });
      }
    },

    /**
     * 选择版本B
     */
    onSelectVersionB(e) {
      const index = e.detail.value;
      const version = this.data.versions[index].VERSION;
      const versionName = this.data.versions[index].VERSION_NAME;
      
      // 防止与版本A相同
      if (version === this.data.versionA) {
        const otherIndex = this.data.versions.findIndex(v => v.VERSION !== version);
        if (otherIndex !== -1) {
          const otherVersion = this.data.versions[otherIndex];
          this.setData({
            versionB: version,
            versionBName: versionName,
            versionBIndex: index,
            versionA: otherVersion.VERSION,
            versionAName: otherVersion.VERSION_NAME,
            versionAIndex: otherIndex,
            showDiff: false
          });
        }
      } else {
        this.setData({
          versionB: version,
          versionBName: versionName,
          versionBIndex: index,
          showDiff: false
        });
      }
    },

    /**
     * 比较版本
     */
    async compareVersions() {
      const { resourceId, versionA, versionB } = this.data;
      
      if (!resourceId || !versionA || !versionB) {
        this.setData({
          error: '请选择要比较的两个版本'
        });
        return;
      }
      
      this.setData({ isComparing: true, error: null });
      
      try {
        // 使用云函数替代Biz调用
        const diffResult = await cloudHelper.callCloudData('research/compare_versions', {
          resourceId,
          versionA,
          versionB
        });
        
        if (diffResult.status === 'error') {
          this.setData({
            isComparing: false,
            error: diffResult.message
          });
          return;
        }
        
        this.setData({
          diffData: diffResult.data,
          isComparing: false,
          showDiff: true
        });
      } catch (err) {
        console.error('比较版本失败', err);
        this.setData({
          isComparing: false,
          error: '比较失败: ' + (err.message || '未知错误')
        });
      }
    }
  }
}) 